<template>
  <BasicModal v-bind="$attrs" @register="registerUserListModal" title="选择用户" @ok="handleSubmit">
    <a-transfer
      :data-source="mockData1"
      :target-keys="targetKeys"
      :disabled="disabled"
      :show-search="showSearch"
      :filter-option="(inputValue, item) => item.title.indexOf(inputValue) !== -1"
      :show-select-all="false"
      @change="onChange"
      :titles="['可选用户列表', '已选中用户列表']"
    >
      <template
        #children="{
          direction,
          selectedKeys,
          disabled: listDisabled,
          onItemSelectAll,
          onItemSelect,
        }"
      >
        <a-table
          :row-selection="
            getRowSelection({
              disabled: listDisabled,
              selectedKeys,
              onItemSelectAll,
              onItemSelect,
            })
          "
          :loading="direction == 'left' ? loading1 : loading2"
          :columns="columns"
          :data-source="direction == 'left' ? data1 : data2"
          :pagination="direction == 'left' ? pagination1 : true"
          @change="handleTableChange"
          size="small"
          :style="{ pointerEvents: listDisabled ? 'none' : null }"
          :custom-row="
            ({ key, disabled: itemDisabled }) => ({
              onClick: () => {
                if (itemDisabled || listDisabled) return;
                onItemSelect(key, !selectedKeys.includes(key));
              },
            })
          "
        />
      </template>
    </a-transfer>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, nextTick, reactive } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { Select, Row, Col, Transfer, Table } from 'ant-design-vue';
  import { difference } from 'lodash-es';
  import { alluserdatabind, selecteduserdatabind } from '/@/api/system/system';

  interface MockData {
    key: string;
    title: string;
    description: string;
    disabled: boolean;
  }
  type tableColumn = Record<string, string>;

  const columnsTable = [
    {
      dataIndex: 'userName',
      title: '用户名',
    },
    {
      dataIndex: 'realName',
      title: '真实姓名',
    },
    {
      dataIndex: 'branchName',
      title: '所属机构',
    },
  ];

  export default defineComponent({
    name: 'MessageUserList',
    components: {
      BasicModal,
      [Select.name]: Select,
      [Row.name]: Row,
      [Col.name]: Col,
      [Transfer.name]: Transfer,
      [Table.name]: Table,
    },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      // const { createMessage } = useMessage();
      const mockData1 = ref<MockData[]>([]);
      const data1 = ref([]);
      const data2 = ref([]);
      const targetKeys = ref<string[]>([]);
      const disabled = ref<boolean>(false);
      const showSearch = ref<boolean>(false);
      const columns = ref<tableColumn[]>(columnsTable);
      const pagination1 = reactive({ current: 1, pageSize: 10, total: 0 });
      const loading1 = ref(false);
      const loading2 = ref(false);

      const [registerUserListModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        nextTick(() => {
          setModalProps({ confirmLoading: false, maskClosable: false, minHeight: 600, width: 960 });
          const useNames = data.useNames;
          getUserDate({ pageNo: 1, pageSize: 10, selectedUser: useNames ? useNames.join() : '' });
          if (useNames) {
            loading2.value = true;
            targetKeys.value = useNames;
            selecteduserdatabind({ selectedUser: targetKeys.value.join() }).then((result) => {
              result.forEach((element) => {
                element.key = element.userName;
                element.title = element.userName;
              });
              data2.value = result;
              mockData1.value.concat(result);
              loading2.value = false;
            });
          }
        });
      });

      const onChange = async (nextTargetKeys: string[]) => {
        targetKeys.value = nextTargetKeys;
        await getUserDate({
          pageNo: pagination1.current,
          pageSize: pagination1.pageSize,
          selectedUser: targetKeys.value.join(),
        });
        loading2.value = true;
        await selecteduserdatabind({ selectedUser: targetKeys.value.join() }).then((result) => {
          result.forEach((element) => {
            element.key = element.userName;
            element.title = element.userName;
          });
          data2.value = result;
          mockData1.value.concat(result);
          loading2.value = false;
        });
      };

      const getRowSelection = ({
        disabled,
        selectedKeys,
        onItemSelectAll,
        onItemSelect,
      }: Record<string, any>) => {
        return {
          getCheckboxProps: (item: Record<string, string | boolean>) => ({
            disabled: disabled || item.disabled,
          }),
          onSelectAll(selected: boolean, selectedRows: Record<string, string | boolean>[]) {
            const treeSelectedKeys = selectedRows
              .filter((item) => !item.disabled)
              .map(({ key }) => key);
            const diffKeys = selected
              ? difference(treeSelectedKeys, selectedKeys)
              : difference(selectedKeys, treeSelectedKeys);
            onItemSelectAll(diffKeys, selected);
          },
          onSelect({ key }: Record<string, string>, selected: boolean) {
            onItemSelect(key, selected);
          },
          selectedRowKeys: selectedKeys,
        };
      };

      /******************************穿梭组件数据***********************************/

      const getUserDate = (params = { pageNo: 1, pageSize: 10, selectedUser: '' }) => {
        loading1.value = true;
        alluserdatabind(params).then((res) => {
          pagination1.total = res.totalCount;
          res.data.forEach((element) => {
            element.key = element.userName;
            element.title = element.userName;
          });
          mockData1.value = res.data;
          data1.value = res.data;
          loading1.value = false;
          if (res.data.length == 0 && params.pageNo != 1) {
            params.pageNo = params.pageNo - 1;
            getUserDate(params);
          }
        });
      };

      const handleTableChange = (pagination) => {
        const pager = { ...pagination };
        pagination1.current = pager.current;
        pagination1.pageSize = pager.pageSize;
        pagination1.total = pager.total;
        getUserDate({
          pageNo: pagination.current,
          pageSize: pagination.pageSize,
          selectedUser: targetKeys.value.join(),
        });
      };

      async function handleSubmit() {
        try {
          closeModal();
          emit('success', targetKeys.value);
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      return {
        registerUserListModal,
        mockData1,
        data1,
        data2,
        loading1,
        loading2,
        pagination1,
        handleTableChange,
        targetKeys,
        disabled,
        showSearch,
        columns,
        onChange,
        getRowSelection,
        handleSubmit,
      };
    },
  });
</script>
